package com.tuojiahr.action;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.tuojiahr.domain.TuoJiaHrUser;
import com.tuojiahr.service.UserService;
import com.tuojiahr.tools.StringUtil;

/**
 * 说明：
 *
 * @author wang.haibo
 * @date 2012-11-11 上午3:14:27
 */

public class LoginAction extends ActionSupport implements ServletResponseAware,
		ServletRequestAware {

	private static final long serialVersionUID = 1L;
	private UserService userService;

	HttpServletRequest request;  
	HttpServletResponse response; 
	
	/**
	 * 管理员登录
	 * @throws IOException
	 */
	public void login() throws IOException {
		String userName=URLDecoder.decode(request.getParameter("userName"),"UTF-8");
		String userPassword=request.getParameter("userPassword");
		String returnMsg = "";
		if(StringUtil.isNotBlank(userName) && StringUtil.isNotBlank(userPassword)) {
			TuoJiaHrUser user = userService.loginUser(userName, userPassword);
			if(null != user) {
				request.getSession().setAttribute("user", user);
				returnMsg = "OK";
			} else{
				returnMsg = "用户或密码错误!";
			}
		} else {
			returnMsg = "用户或密码错误";
		}
		
		response.getWriter().write(returnMsg);
		response.getWriter().close();
	}
	
	/**
	 * 注销session 
	 */
	public void sessionDestroy() throws Exception {
		
		request.getSession().invalidate();
		
		response.sendRedirect(request.getContextPath()+"/admin_index.jsp");
	}
	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
